<?php defined('SYSPATH') or die('No direct script access.');
/**
 * $Id: post.php 51 2008-07-29 07:19:08Z geertdd $
 *
 * @package    PianissiBoard
 * @author     Geert De Deckere
 */
class Post_Controller extends Pianissibase_Controller {

	/**
	 * URL: /pianissiboard/post[/topic/{id}]
	 * Create a new topic or reply to an existing one.
	 */
	public function index()
	{
		// Reply to an existing topic
		if ( ! $new_topic = ! (bool) ($topic_id = (int) $this->uri->segment(4)))
		{
			// Non-existing topic id
			if ( ! $topic = $this->topic->get_by_id($topic_id))
				Event::run('system.404');

			// Topic has been closed
			if ($topic->closed)
			{
				$this->session->set_flash('message', 'You can no longer reply to this topic because it has been closed.');
				url::redirect('pianissiboard/topic/'.$topic->id);
			}
		}

		// Setup template
		$this->template->pagetitle = ($new_topic) ? 'Post new topic' : 'Reply to “'.$topic->title.'”';
		$this->template->content = new View('pianissiboard/postform');
		$this->template->content->preview = FALSE;
		$this->template->content->new_topic = $new_topic;
		$this->template->content->topic = ($new_topic) ? NULL : $topic;

		// Initialize all form fields
		$form = array
		(
			'title'    => '',
			'author'   => (string) cookie::get('author'),
			'email'    => (string) cookie::get('email'),
			'website'  => (string) cookie::get('website', 'http://'),
			'post'     => '',
			'remember' => isset($_COOKIE['author']),
		);

		// Form not submitted
		if ( ! $_POST)
		{
			// Intialize (empty) form fields in view
			$this->template->content->postform = (object) $form;
		}

		// Form submitted
		else
		{
			// Validation setup
			$post = Validation::factory($_POST);
			$post->pre_filter('trim');
			$post->pre_filter('format::url', 'website');

			// Check topic title first
			if ($new_topic)
			{
				$post->add_rules('title', 'required', 'url::title', 'length[1,100]');
			}

			$post->add_rules('post', 'required', 'length[1,5000]');
			$post->add_rules('author', 'required', 'length[1,100]');

			// Require e-mail address
			if (Kohana::config('pianissiboard.require_email') === TRUE)
			{
				$post->add_rules('email', 'required');
			}

			$post->add_rules('email', 'email', 'length[1,100]');
			$post->add_rules('website', 'url', 'length[0,100]');

			// Captcha enabled
			if (Kohana::config('pianissiboard.enable_captcha') === TRUE)
			{
				$post->add_rules('captcha', 'Captcha::valid');
			}

			// Run validation
			$validate = $post->validate();

			// Overwrite initial form values
			$form = arr::overwrite($form, $post->as_array());

			// Repopulate form (needed in case of errors or preview)
			$this->template->content->postform = (object) $form;

			// Errors
			if ( ! $validate)
			{
				$this->template->content->formerrors = $post->errors('formerrors');
			}

			// Show preview
			elseif ( ! isset($_POST['confirm']))
			{
				$this->template->content->preview = TRUE;

				// Prepare and set preview post data
				$form['date'] = time();
				$this->template->content->post = (object) $form;
			}

			// No errors and no preview
			else
			{
				// Add topic to database
				if ($new_topic)
				{
					$form['slug'] = url::title($form['title']);
					$topic->id = $this->topic->add($form);
				}

				// Add post to database
				$form['topic_id'] = $topic->id;
				$post->id = $this->post->add($form);

				// Remember personal data
				if (isset($_POST['remember']))
				{
					cookie::set('author', $form['author'], Kohana::config('pianissiboard.cookie_lifetime'));
					cookie::set('email', $form['email'], Kohana::config('pianissiboard.cookie_lifetime'));
					cookie::set('website', $form['website'], Kohana::config('pianissiboard.cookie_lifetime'));
				}
				// Remove cookies
				else
				{
					(isset($_COOKIE['author'])) and cookie::delete('author');
					(isset($_COOKIE['email'])) and cookie::delete('email');
					(isset($_COOKIE['website'])) and cookie::delete('website');
				}

				// Redirect to topic
				if ($new_topic)
				{
					$this->session->set_flash('message', 'Your topic has been created.');
					url::redirect('pianissiboard/topic/'.$topic->id.'/'.$form['slug']);
				}
				// Redirect to post
				else
				{
					$this->session->set_flash('message', 'Your reply has been posted.');
					url::redirect($this->post->url($post->id, $topic->id));
				}
			}
		}
	}

}